package com.shop.cloud.controller.user;

import io.swagger.annotations.ApiOperation;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.shop.cloud.common.mybatis.BaseController;
import com.shop.cloud.dao.hongfu.UserDao;
import com.shop.cloud.domain.hongfu.BalanceHistory;
import com.shop.cloud.domain.hongfu.Bank;
import com.shop.cloud.domain.hongfu.BankAccount;
import com.shop.cloud.domain.hongfu.InviteHistory;
import com.shop.cloud.domain.hongfu.PointsHistory;
import com.shop.cloud.domain.hongfu.SafetyCode;
import com.shop.cloud.domain.hongfu.SysConfig;
import com.shop.cloud.domain.hongfu.User;
import com.shop.cloud.domain.hongfu.UserAddress;
import com.shop.cloud.domain.hongfu.UserConfig;
import com.shop.cloud.domain.hongfu.UserLevel;
import com.shop.cloud.domain.hongfu.UserLoginHistory;
import com.shop.cloud.domain.hongfu.UserMember;
import com.shop.cloud.domain.hongfu.UserVip;
import com.shop.cloud.domain.system.SysRole;
import com.shop.cloud.filter.CurrentUserId;
import com.shop.cloud.model.request.AddUserRequest;
import com.shop.cloud.model.request.EditParentUserRequest;
import com.shop.cloud.model.request.GetBalanceListRequest;
import com.shop.cloud.model.request.GetParentUserListRequest;
import com.shop.cloud.model.request.GetUserInfoRequest;
import com.shop.cloud.model.request.GetUserLevelListRequest;
import com.shop.cloud.model.request.GetUserListRequest;
import com.shop.cloud.model.request.UpdateUserLevelRequest;
import com.shop.cloud.model.response.AddUserResponse;
import com.shop.cloud.model.response.EditParentUserResponse;
import com.shop.cloud.model.response.GetBalanceListResponse;
import com.shop.cloud.model.response.GetParentUserListResponse;
import com.shop.cloud.model.response.GetUserInfoResponse;
import com.shop.cloud.model.response.GetUserLevelListResponse;
import com.shop.cloud.model.response.GetUserListResponse;
import com.shop.cloud.model.response.UpdateUserLevelResponse;
import com.shop.cloud.security.EncodeUtil;
import com.shop.cloud.service.hongfu.UserMemberService;
import com.shop.cloud.service.hongfu.UserVipService;
import com.shop.cloud.service.hongfu.impl.BalanceHistoryService;
import com.shop.cloud.service.hongfu.impl.BankAccountService;
import com.shop.cloud.service.hongfu.impl.BankService;
import com.shop.cloud.service.hongfu.impl.InviteHistoryService;
import com.shop.cloud.service.hongfu.impl.PointsHistoryService;
import com.shop.cloud.service.hongfu.impl.SafetyCodeService;
import com.shop.cloud.service.hongfu.impl.ShopService;
import com.shop.cloud.service.hongfu.impl.SysConfigService;
import com.shop.cloud.service.hongfu.impl.UserAddressService;
import com.shop.cloud.service.hongfu.impl.UserConfigService;
import com.shop.cloud.service.hongfu.impl.UserLevelService;
import com.shop.cloud.service.hongfu.impl.UserLoginHistoryService;
import com.shop.cloud.service.hongfu.impl.UserService;
import com.shop.cloud.service.hongfu.impl.WithdrawHistoryService;
import com.shop.cloud.service.system.impl.SysRoleService;
import com.shop.cloud.util.ErrorCode;
import com.shop.cloud.util.Page;
import com.shop.cloud.util.Response;
import com.shop.cloud.util.ResponseUtil;

@RestController
@RequestMapping(value = "user")
public class UserController extends BaseController {

	private static final Logger logger = Logger.getLogger(UserController.class);

	@Autowired
	private UserService userService;
	
	@Autowired
	private UserLevelService userLevelService;

	@Autowired
	private ShopService shopService;
	
	@Autowired
	private SysRoleService sysRoleService;
	
	@Autowired
	private SysConfigService sysConfigService;
	
	@Autowired
	private PointsHistoryService pointsHistoryService;
	
	@Autowired
	private UserConfigService userConfigService;
	
	@Autowired
	private BalanceHistoryService balanceHistoryService;
	
	@Autowired
	private UserAddressService userAddressService;
	
	@Autowired
	private UserDao userDao;
	
	@Autowired
	private UserLoginHistoryService userLoginHistoryService;
	
	@Autowired
	private InviteHistoryService inviteHistoryService;
	
	@Autowired
	private WithdrawHistoryService withdrawHistoryService;
	
	@Autowired
	private BankService bankService;

	@Autowired
	private BankAccountService bankAccountService;
	
	@Autowired
	private SafetyCodeService safetyCodeService;
	
	@Autowired
	private UserMemberService userMemberService;
	
	@Autowired
	private UserVipService userVipService;
	

	@ApiOperation(value = "获取前台用户列表", notes = "获取前台用户列表")
	@RequestMapping(value = "list", method = RequestMethod.POST)
	@ResponseBody
	public Response list(HttpServletRequest request, HttpServletResponse response,@CurrentUserId Long userId,@RequestBody GetUserListRequest userListRequest) {
		logger.debug("获取前台用户列表");
		
		
		
		List<GetUserListResponse> datas = new ArrayList<GetUserListResponse>();
		GetUserListResponse data = null;
		Map<String, Object> params = getPageMap(request);
		List<User> users = null;
		User user = null;
		SysRole sysRole = null;
		int i = 0;
		
		//用户权限
		User user2 = userDao.getRoleId(userId);
		if (user2.getAuthority()==1) {
//			params.put("roleId",user2.getRoleId());
		}
		
		if (user2.getAuthority()==2) {
			params.put("roleId",user2.getRoleId());
		}
		
		if(!(userListRequest.getRoleId() == null || userListRequest.getRoleId().equals(""))){
			params.put("roleId", userListRequest.getRoleId());
		}
		if(!(userListRequest.getLevel() == null || userListRequest.getLevel().equals(""))){
			params.put("level", userListRequest.getLevel());
		}
		if(!(userListRequest.getStart_time() == null || userListRequest.getStart_time().equals(""))){
			params.put("startTime", userListRequest.getStart_time());
		}
		if(!(userListRequest.getEnd_time() == null || userListRequest.getEnd_time().equals(""))){
			params.put("endTime", userListRequest.getEnd_time());
		}
		//搜索类型。1搜索用户ID，2搜索用户姓名，3搜索手机号，4搜索会员卡号。
		if((userListRequest.getSearchType() >0 ) && !(userListRequest.getKey() == null || userListRequest.getKey().equals(""))) {
			switch(userListRequest.getSearchType()) {
			case GetUserListRequest.SEARCH_TYPE_USER_ID :
				params.put("id", userListRequest.getKey());
				break;
			case GetUserListRequest.SEARCH_TYPE_USER_NAME :
				params.put("nickname", userListRequest.getKey());
				break;
			case GetUserListRequest.SEARCH_TYPE_PHONE :
				params.put("phone", userListRequest.getKey());
				break;
			case GetUserListRequest.SEARCH_TYPE_CARD_NO :
				params.put("member_card", userListRequest.getKey());
				break;
			default :
				break;
			}
		}
		params.put("orderBy", "create_time desc");
		long count = userService.count(params);
		
		int pageIndex = userListRequest.getPageIndex_();
		int pageSize = userListRequest.getPageSize_();
		Page<GetUserListResponse> page = new Page<GetUserListResponse>(pageIndex,pageSize);
		int limitStart = (pageIndex - 1) * pageSize;
		params.put("limitStart", limitStart);
		
		int limitEnd = pageSize;
		params.put("limitEnd", limitEnd);
		
		users = userService.find(params);
		
		if (users != null) {
			for (i = 0; i < users.size(); i++) {
				user = users.get(i);
				data = new GetUserListResponse();
				data.setId(user.getId());
				data.setNickname(user.getNickname());
				data.setUsername(user.getNickname());					// nickname == username
				data.setPhone(user.getPhone());
				data.setCardno(user.getMemberCard());
//				data.setChannel("AppStore");								// channel 
				data.setLevel(String.valueOf(user.getType()) + "级");	// 级别
				data.setBalance(user.getBalance());
				data.setPoints(user.getPoints());
				data.setCanWithdrawBalance(user.getCanWithdrawBalance());
				data.setRebateBalance(user.getCanRebateBalance());
				params = new HashMap<String, Object>();
				params.put("id", user.getRoleId());
				sysRole = sysRoleService.findOne(params);
				if(sysRole != null) {
					data.setStore(sysRole.getName());
				} else {
					data.setStore("");
				}
				data.setCreate_time(user.getCreateTime());
				
				//查询最后登陆时间
				UserLoginHistory userLoginHistory = new UserLoginHistory();
				userLoginHistory.setUserId(user.getId());
				userLoginHistory.setOrderBy("USER_LOGIN_HISTORY.logout_time desc");
				userLoginHistory = userLoginHistoryService.findOne(userLoginHistory);
				if (userLoginHistory!=null) {
					
					data.setLast_login_time(userLoginHistory.getLoginTime());
				}else {
					data.setLast_login_time(user.getCreateTime());
				}
				
				datas.add(data);
			}
		}
		
		page.setData(datas);
		page.setTotalCount((int)count);

		return ResponseUtil.ok(page);

	}
	
//	@ApiOperation(value = "获取前台用户列表", notes = "获取前台用户列表")
//	@RequestMapping(value = "list", method = RequestMethod.POST)
//	@ResponseBody
//	public Response find(@CurrentUserId Long userId,@RequestBody User user){
//		user.setOrderBy("USER.create_time DESC");
//		Page<User> datas=userService.page(user);
//		return ResponseUtil.ok(datas);
//	}
	
	@ApiOperation(value = "获取用户帐户变动列表", notes = "获取用户帐户变动列表")
	@RequestMapping(value = "balancelist", method = RequestMethod.POST)
	@ResponseBody
	public Response balancelist(HttpServletRequest request, HttpServletResponse response,@RequestBody GetBalanceListRequest balanceListRequest) {
		List<GetBalanceListResponse> datas = new ArrayList<GetBalanceListResponse>();
		GetBalanceListResponse data = null;
		Map<String, Object> params = getPageMap(request);
		User user = null;
		int i = 0;
		List<BalanceHistory> balanceHistorys = null;
		List<PointsHistory> pointsHistories = null;
		BalanceHistory balanceHistory = null;
		
		if(balanceListRequest.getUserId() == null || balanceListRequest.getUserId() <= 0) {
			return ResponseUtil.error(ErrorCode.INSERT_DATA_ERROR, "非法操作");
		}
		
		user = userService.get(balanceListRequest.getUserId());
		if(user == null) {
			return ResponseUtil.error(ErrorCode.INSERT_DATA_ERROR, "无此用户");
		}
		
		params = new HashMap<String, Object>();
		params.put("userId", balanceListRequest.getUserId());
		//金额
		balanceHistorys = balanceHistoryService.find(params);
		//积分
		pointsHistories = pointsHistoryService.find(params);
		if (pointsHistories!=null) {
			for (int j = 0; j < pointsHistories.size(); j++) {
				PointsHistory pointsHistory = pointsHistories.get(j);
				data = new GetBalanceListResponse();
				data.setAmount(String.valueOf(pointsHistory.getChangePoints())+"积分");
				data.setStatus("交易成功");
				data.setTime(pointsHistory.getCreateTime());
				if (pointsHistory.getType()==1) {
					data.setType("每日签到");
				}
				if (pointsHistory.getType()==2) {
					data.setType("购买积分产品");
				}
				if (pointsHistory.getType()==3) {
					data.setType("邀请好友获得");
				}
				if (pointsHistory.getType()==4) {
					data.setType("注册赠送");
				}
				if (pointsHistory.getType()==5) {
					data.setType("系统赠送");
				}
				if (pointsHistory.getType()==6) {
					data.setType("系统扣除");
				}
				if (pointsHistory.getType()==7) {
					data.setType("购买积分产品退还");
				}
				datas.add(data);
			}
		}
		if (balanceHistorys != null) {
			for (i = 0; i < balanceHistorys.size(); i++) {
				balanceHistory = balanceHistorys.get(i);
				data = new GetBalanceListResponse();
				data.setId(balanceHistory.getId());
				if (balanceHistory.getType() ==1 || balanceHistory.getType() ==2 || balanceHistory.getType() ==4 || balanceHistory.getType() ==8 || balanceHistory.getType() ==9 || balanceHistory.getType() ==11 || balanceHistory.getType() ==12 || balanceHistory.getType() ==15 || balanceHistory.getType() ==16 || balanceHistory.getType() ==17) {
					if (balanceHistory.getType() ==2 || balanceHistory.getType() ==4  || balanceHistory.getType() ==9 || balanceHistory.getType() ==12 || balanceHistory.getType() ==20) {
						data.setAmount("-"+String.valueOf(balanceHistory.getAmount()) + "元");
					}else {
						data.setAmount(String.valueOf(balanceHistory.getAmount()) + "元");
					}
					data.setTime(balanceHistory.getCreateTime());
					data.setStatus("交易成功");
					switch(balanceHistory.getType()) {
					case 1 :
						data.setType("充值");
						break;
					case 2 :
						data.setType("购买福乐康商品");
						break;
//				case 3 :
//					data.setType("购买积分商品");
//					break;
					case 4 :
						data.setType("购买旅游商品");
						break;
//				case 5 :
//					data.setType("积分赠送");
//					break;
//				case 6 :
//					data.setType("注册赠送");
//					break;
//				case 7 :
//					data.setType("每日签到");
//					break;
					case 8 :
						data.setType("系统赠送");
						break;
					case 9 :
						data.setType("系统扣除");
						break;
//				case 10 :
//					data.setType("邀请好友");
//					break;
					case 11 :
						data.setType("分销提成");
						break;
					case 12 :
						data.setType("报名活动");
						break;
//				case 13 :
//					data.setType("积分赠送");
//					break;
//				case 14 :
//					data.setType("积分代扣");
//					break;
					case 15 :
						data.setType("报名活动退款");
						break;
					case 16 :
						data.setType("购买福乐康商品退款");
						break;
					case 17 :
						data.setType("购买旅游商品退款");
						break;
					case 18 :
						data.setType("可提现余额");
						break;
					default :
						data.setType("未知");
						break;
					}
					datas.add(data);
				}
			}
		}

		return ResponseUtil.ok(datas);

	}
	
//	@ApiOperation(value = "获取用户帐户变动列表", notes = "获取用户帐户变动列表")
//	@RequestMapping(value = "balancelist", method = RequestMethod.POST)
//	@ResponseBody
//	public Response balancelist(@CurrentUserId Long userId, @RequestBody BalanceHistory balanceHistory){
//		List<BalanceHistory> datas = balanceHistoryService.find(balanceHistory);
//		return ResponseUtil.ok(datas);
//	}
	
	//@MagicPermission
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public Response add(@CurrentUserId Long userId, HttpServletRequest request, HttpServletResponse response, @RequestBody AddUserRequest addUserRequest){
		logger.debug("添加用户");
		AddUserResponse addUserResponse = new AddUserResponse();
		User user = null;
		PointsHistory pointsHistory = new PointsHistory();
 		int givePoint = 20;
		Timestamp currentTime = new Timestamp((new java.util.Date()).getTime());
		Map<String, Object> params = null;
		SysConfig sysConfig = getSysConfig(SysConfig.CONFIG_SHARE_BASE_URL);
		UserConfig userConfig = new UserConfig();
		
		sysConfig = getSysConfig(SysConfig.CONFIG_REGISTER_GIVE_POINTS);
     	if(sysConfig != null) {
     		givePoint = Integer.parseInt(sysConfig.getValue());
     	}
		
		if(addUserRequest.getNickName().equals("") ||
		   (addUserRequest.getSex() != User.SEX_MALE && addUserRequest.getSex() != User.SEX_FEMALE) ||
		   addUserRequest.getMobile().equals("") ||
		   addUserRequest.getPassword().equals("") ||
		   addUserRequest.getStoreId() <= 0 ||
		   addUserRequest.getLevel() <= 0) {
			return ResponseUtil.error(ErrorCode.INSERT_DATA_ERROR, "有必填项未填写");
		}
		
		params = new HashMap<String, Object>();
		params.put("eqphone", addUserRequest.getMobile());
		user = userService.findOne(params);
		if(user != null) {
			return ResponseUtil.error(ErrorCode.INSERT_DATA_ERROR, "已存在此账号");
		}
		
		user = new User();
		user.setPhone(addUserRequest.getMobile());
		user.setNickname(addUserRequest.getNickName());
		user.setSex(addUserRequest.getSex());
		user.setLevel(addUserRequest.getLevel());
		user.setRoleId(addUserRequest.getStoreId());
		user.setPortrait("");							// 还未设置
		user.setPassword(EncodeUtil.encodeMD5(addUserRequest.getPassword()));
		user.setRegionId(0L);
		user.setBirthday(null);
		user.setInviteCode("");
		user.setQqAccount("");
		user.setWeixinAccount("");
		user.setWeiboAccount("");
		user.setCreateTime(currentTime);
		user.setMemberCard(addUserRequest.getCardNumber());
		user.setBalance(0.0f);
		user.setPoints(givePoint);
		user.setTotalPoints(0);
		user.setTotalRewardBalance(0.0f);
		user.setCanRebateBalance(0.0f);
		user.setCanWithdrawBalance(0.0f);
		user.setCanWithdrawBalanceRebate(0.0f);
		user.setCanWithdrawBalanceInfund(0.0f);
		user.setTotalConsumeAmount(0.0f);
		user.setAlreadyRebateBalance(0.0f);
		user.setWaitRebateBalance(0.0f);
		user.setRemainConsumeAmount(0.0f);
		user.setInviterUserId(0L);
		user.setType(addUserRequest.getLevel());
		
		if(!userService.insert(user)) {
			return ResponseUtil.error(ErrorCode.INSERT_DATA_ERROR, "插入失败");
		}
		params = new HashMap<String, Object>();
 		params.put("eqphone", user.getPhone());
 		user = userService.findOne(params);
 		
 		// 更新自身的邀请代码
 		user.setInviteCode(String.valueOf(user.getId()));
//		String filePath = FileUtils.getUserDirectoryPath();
//     	String fileName = "qrcode" + String.valueOf(UniqueIdGenerator.getUniqueId()) + ".png";
//     	String qrCode = fileName;
//		try {
////			QRCodeUtils.encode(sysConfig.getValue() + "/" + "invite.html?code=" + user.getInviteCode(), filePath, fileName);
//		} catch (WriterException | IOException e) {
//			e.printStackTrace();
//			return ResponseUtil.error(ErrorCode.INSERT_DATA_ERROR, "插入失败");
//		}
//		user.setQrcode(qrCode);
 		userService.update(user);
		
 		// 添加用户积分记录
 		pointsHistory = new PointsHistory();
     	pointsHistory.setChangePoints(givePoint);
     	pointsHistory.setCurrentPoints(givePoint);
     	pointsHistory.setCreateTime(currentTime);
     	pointsHistory.setType(PointsHistory.POINT_TYPE_REGISTER);
     	pointsHistory.setUserId(user.getId());
        // 订单编号
 		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
 		java.util.Date date = new java.util.Date();
 		String str = simpleDateFormat.format(date);
 		Random random = new Random();
 		int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;// 获取5位随机数
 		String orderNo = str + rannum;// 当前时间
 		pointsHistory.setPointNo(orderNo);
     	pointsHistoryService.insert(pointsHistory);
     	
     	// 添加用户配置
     	userConfig = new UserConfig();
     	userConfig.setUserId(user.getId());
     	userConfig.setEnableAlarm(1);
     	userConfig.setEnableSysMessageNotice(1);
     	userConfig.setEnableVoice(1);
     	userConfigService.insert(userConfig);
		
		return ResponseUtil.ok(addUserResponse);
	}
	
	@ApiOperation(value = "获取用户等级列表", notes = "获取用户等级列表")
	@RequestMapping(value = "levelList", method = RequestMethod.POST)
	@ResponseBody
	public Response list(HttpServletRequest request, HttpServletResponse response,@RequestBody GetUserLevelListRequest userLevelListRequest) {
		List<GetUserLevelListResponse> datas = new ArrayList<GetUserLevelListResponse>();
		GetUserLevelListResponse data = null;
		Map<String, Object> params = getPageMap(request);
		List<UserLevel> userLevels = null;
		UserLevel userLevel = null;
		int i = 0;
		
		params.put("orderBy", "level asc");
		userLevels = userLevelService.find(params);
		if(userLevels != null) {
			for(i = 0 ; i < userLevels.size() ; i++) {
				userLevel = userLevels.get(i);
				data = new GetUserLevelListResponse();
				data.setId(userLevel.getId());
				data.setIsDefault(userLevel.getIsDefault());
				data.setLevel(userLevel.getLevel());
				data.setLevelStr("级别" + userLevel.getLevel());
				data.setName(userLevel.getName());
				datas.add(data);
			}
		}
		
		return ResponseUtil.ok(datas);
	}
	
	@ApiOperation(value = "更新用户等级", notes = "更新用户等级")
	@RequestMapping(value = "updateLevel", method = RequestMethod.POST)
	@ResponseBody
	public Response updateLevel(HttpServletRequest request, HttpServletResponse response,@RequestBody UpdateUserLevelRequest updateUserLevelRequest) {
		logger.debug(">>>>>>>>更新用户等级<<<<<<<<<<");
		UpdateUserLevelResponse data = new UpdateUserLevelResponse();
		UserLevel userLevel = null;
		List<UserLevel> list = null;
		
		if (updateUserLevelRequest != null && !updateUserLevelRequest.equals("")) {
			list = updateUserLevelRequest.getLevels();
			if (list != null && list.size() != 0) {
				for (UserLevel ul : list) {
					 userLevel = new UserLevel();
					 userLevel.setId(ul.getId());
					 userLevel.setLevel(ul.getLevel());
					 userLevel.setName(ul.getName());
					 userLevel.setIsDefault(ul.getIsDefault());
					userLevelService.update(userLevel);
				}
			}
		}
		return ResponseUtil.ok(data);
	}
	
	@ApiOperation(value = "获取用户等级", notes = "获取用户等级")
	@RequestMapping(value = "/levelLists", method = RequestMethod.POST)
	@ResponseBody
	public Response levelLists(@CurrentUserId Long userId, @RequestBody UserLevel userLevel){
		userLevel.setOrderBy("USER_LEVEL.level");
		Page<UserLevel> data = userLevelService.page(userLevel);
		return ResponseUtil.ok(data);
	}
	
	@ApiOperation(value = "修改用户等级", notes = "修改用户等级")
	@RequestMapping(value = "/updateLevels", method = RequestMethod.POST)
	@ResponseBody
	public Response updateLevels(@CurrentUserId Long userId, @RequestBody UserLevel userLevel){
		userLevelService.findIsDefault(userLevel);
		userLevel.setIsDefault(0);
		int success = userLevelService.update(userLevel);
		
		return ResponseUtil.ok(success);
	}
	
	@ApiOperation(value = "获取用户信息", notes = "获取用户信息")
	@RequestMapping(value = "info", method = RequestMethod.POST)
	@ResponseBody
	public Response info(HttpServletRequest request, HttpServletResponse response,@RequestBody GetUserInfoRequest getUserInfoRequest) {
		logger.debug(">>>>>>>>获取用户信息<<<<<<<<<<");
		GetUserInfoResponse data = new GetUserInfoResponse();
		User user = null;
		UserAddress userAddress = null;
		UserAddress returnUserAddress = null;
//		Region region = null;
		UserLevel userLevel = null;
		
		if (getUserInfoRequest != null && !getUserInfoRequest.equals("")) {
			user = new User();
			user.setId(getUserInfoRequest.getId());
			List<User> returnUserInfo = userService.find(user);
			
			userAddress = new UserAddress();
			userAddress.setUserId(getUserInfoRequest.getId());
			List<UserAddress> listUserAddress = userAddressService.find(userAddress);
			
			//地址内信息
			if (listUserAddress != null && listUserAddress.size() > 0) {
				returnUserAddress = listUserAddress.get(0);
				data.setAddressName(returnUserAddress.getName());
				data.setAddressPhone(returnUserAddress.getPhone());
			}
			
			if (returnUserInfo != null && returnUserInfo.size() > 0 ) {
				user = returnUserInfo.get(0);
				data.setId(user.getId());
//				if (user.getPortrait() != null && !user.getPortrait().trim().equals("") && user.getPortrait().trim().length() > 0 ) {
//					data.setHeadPortrait(Long.valueOf(user.getPortrait().trim()));
//				}
				data.setUserLevel(user.getUserLevel());
				data.setPortrait(user.getPortrait());
				data.setNickname(user.getNickname());
				data.setUsername(user.getNickname());
				data.setSex(String.valueOf(user.getSex()));
				data.setPhone(user.getPhone());
				data.setCardno(user.getMemberCard());
	//TODO 这里没有身份证号码。。。 
				data.setIdentify("");//没有身份证号码
				data.setBirthday(user.getBirthday());
	//TODO 仅通过regionId 无法获得省市区  
				data.setArea("");
//				user.getRegionId()+
	//TODO 没有channel 值
				data.setChannel("");
				
				if (user.getLevel()!=null ) {
					userLevel = new UserLevel();
					userLevel.setLevel(user.getType());
					List<UserLevel> listUserLevel = userLevelService.find(userLevel);
					if (listUserLevel != null && listUserLevel.size() > 0 && listUserLevel.get(0) != null) {
						userLevel = listUserLevel.get(0);
						data.setLevel(userLevel.getName());
					}
				}
	//TODO 没有store 字段
				data.setStore(user.getRoleId().toString());
				data.setCreate_time(user.getCreateTime());
	//TODO 没有最后登录时间
				data.setLast_login_time(new Date());
				
				if (returnUserAddress != null) {
					List<String> list = new ArrayList<String>();
					list.add(returnUserAddress.getAddress());
					data.setAddresses(list);
				}
				
				//提现账户
				BankAccount bankAccount = new BankAccount();
				bankAccount.setUserId(getUserInfoRequest.getId());
				List<BankAccount> bankAccounts = bankAccountService.find(bankAccount);
				if (null !=bankAccounts && bankAccounts.size()>0) {
					for (BankAccount bankAccount2 : bankAccounts) {
						Bank bank = new Bank();
						bank.setId(bankAccount2.getBankId());
						Bank bank2 =bankService.findOne(bank);
						bankAccount2.setBankName(bank2.getName());
					}
					data.setBankAccounts(bankAccounts);
				}
			}
		}
		return ResponseUtil.ok(data);
	}
	
//	@ApiOperation(value = "修改用户信息", notes = "修改用户信息")
//	@RequestMapping(value = "edit", method = RequestMethod.POST)
//	@ResponseBody
//	public Response edit(HttpServletRequest request, HttpServletResponse response,@RequestBody EditUserInfoRequest editUserInfoRequest) {
//		logger.debug(">>>>>>>>修改用户信息<<<<<<<<<<");
//		EditUserInfoResponse data = new EditUserInfoResponse();
//		User user = new User();
//	
//		//修改类型。 type  1头像，2用户昵称，3级别，4所属门店
//		int flag = editUserInfoRequest.getType();
//		
//		if (flag == 1) {//头像
//			user.setId(editUserInfoRequest.getId());
//			user.setPortrait(editUserInfoRequest.getValue());
//		}
//		if (flag == 2) {//用户昵称
//			user.setId(editUserInfoRequest.getId());
//			user.setNickname(editUserInfoRequest.getValue());
//		}
//		if (flag == 3) {//级别
//			user.setId(editUserInfoRequest.getId());
//			user.setLevel(Integer.valueOf(editUserInfoRequest.getValue()));
//		}
//		if (flag == 4) {//所属门店
//			user.setId(editUserInfoRequest.getId());
//			user.setRoleId(Long.valueOf(editUserInfoRequest.getValue()));
//		}
//		int line = userService.update(user);
//		if (line <= 0) {
//			return ResponseUtil.error(ErrorCode.UPDATE_DATA_ERROR);
//		}
//		return ResponseUtil.ok(data);
//	}
	
	@ApiOperation(value = "修改用户信息", notes = "修改用户信息")
	@RequestMapping(value = "updateInfo", method = RequestMethod.POST)
	@ResponseBody
	public Response update(@CurrentUserId Long userId,@RequestBody User user){
		user.setType(user.getLevel());
		int success = userService.update(user);
		return ResponseUtil.ok(success);
	}
	
//	@ApiOperation(value = "获取下级用户列表", notes = "获取下级用户列表")
//	@RequestMapping(value = "sonList", method = RequestMethod.POST)
//	@ResponseBody
//	public Response sonlist(HttpServletRequest request, HttpServletResponse response,@RequestBody GetSonUserListRequest sonUserListRequest) {
//		logger.debug(">>>>>>>>获取下级用户列表<<<<<<<<<<");
//		List<GetSonUserListResponse> datas = new ArrayList<GetSonUserListResponse>();
//		GetSonUserListResponse data = null;
//		Map<String, Object> params = null;
//		List<User> users = null;
//		User user = null;
//		User findUser = null; 
//		
//		params = getPageMap(request);
//		params.put("id", sonUserListRequest.getId());
//		params.put("orderBy", "level asc");
//		
//		users = userService.find(params);
//		if (users !=null && users.size() > 0 && users.get(0) != null) {
//			user = users.get(0);
//			Long inviterUserId = user.getInviterUserId();
//			
//			findUser = new User();
//			findUser.setInviterUserId(inviterUserId);
//			List<User> resultUser = userService.find(findUser);
//			
//			if (resultUser != null && resultUser.size() > 0) {
//				for (User u : resultUser) {
//					data = new GetSonUserListResponse();
//					data.setUserId(u.getId());
//					data.setLevelStr(String.valueOf(user.getLevel()) + "级");
//					data.setNickName(u.getNickname());
//					
//					datas.add(data);
//				}
//			}
//		}
//		return ResponseUtil.ok(datas);
//	}
	
//	@ApiOperation(value = "获取用户上级", notes = "获取用户上级")
//	@RequestMapping(value = "/parentLists", method = RequestMethod.POST)
//	@ResponseBody
//	public Response parentLists(@CurrentUserId Long userId, @RequestBody User user){
//		Page<User> data = userService.page(user);
//		return ResponseUtil.ok(data);
//	}
//	
	@ApiOperation(value = "获取用户下级", notes = "获取用户下级")
	@RequestMapping(value = "/sonList", method = RequestMethod.POST)
	@ResponseBody
	public Response sonLists(@CurrentUserId Long userId, @RequestBody User user){
		List<User> data = userService.finddown(user);
		return ResponseUtil.ok(data);
	}
	
	@ApiOperation(value = "获取上级用户列表", notes = "获取上级用户列表")
	@RequestMapping(value = "parentList", method = RequestMethod.POST)
	@ResponseBody
	public Response parentlist(HttpServletRequest request, HttpServletResponse response,@RequestBody GetParentUserListRequest parentUserListRequest) {
		logger.debug(">>>>>>>>获取上级用户列表<<<<<<<<<<");
		List<GetParentUserListResponse> datas = new ArrayList<GetParentUserListResponse>();
		GetParentUserListResponse data = null;
		Map<String, Object> params = null;
		List<User> users = null;
		User user = null;
		boolean flag = true;//是否继续查找上级
		Long invinterUserId = null;
		
		//查询邀请上级
		InviteHistory inviteHistory = new InviteHistory();
		inviteHistory.setInviteUserId(parentUserListRequest.getId());
		List<InviteHistory> inviteHistorieList = inviteHistoryService.find(inviteHistory);
		for (InviteHistory inviteHistory2 : inviteHistorieList) {
			//如果是二级用户
			User user2 =userService.get(inviteHistory2.getUserId());
			data = new GetParentUserListResponse();
			data.setLevelStr(user2.getType()+"级");
			data.setNickName(user2.getNickname());
			data.setUserId(user2.getId());
			datas.add(data);
			//如果是三级用户
			inviteHistory = new InviteHistory();
			inviteHistory.setInviteUserId(inviteHistory2.getUserId());
			List<InviteHistory> inviteHistorieList2 = inviteHistoryService.find(inviteHistory);
			for (InviteHistory inviteHistory3 : inviteHistorieList2) {
				User user3 =userService.get(inviteHistory3.getUserId());
				data = new GetParentUserListResponse();
				data.setLevelStr(user3.getType()+"级");
				data.setNickName(user3.getNickname());
				data.setUserId(user3.getId());
				datas.add(data);
			}
			
		}
		
		params = getPageMap(request);
		params.put("id", parentUserListRequest.getId());
		params.put("orderBy", "type asc");
		
		users = userService.find(params);
		if (users != null && users.size() > 0) {
			user = users.get(0);
			invinterUserId = user.getInviterUserId();
		}
		
		while (flag) {//循环查询上级客户
			if (invinterUserId != null ) {
				user = new User();
				user.setId(invinterUserId);
				users = userService.find(user);
				
				if (users != null && !users.equals("") && users.size() > 0) {
					for (User u : users) {
						data = new GetParentUserListResponse();
						data.setLevelStr(u.getType()+"级");
						data.setNickName(u.getNickname());
						data.setUserId(u.getId());
						
						datas.add(data);
						
						if (u.getInviterUserId() != null && !u.getInviterUserId().equals("") && invinterUserId != u.getInviterUserId()) {
							invinterUserId = u.getInviterUserId();
						}else {
							invinterUserId = null;
							flag = false;
							break;
						}
					}
				}else {
					invinterUserId = null;
					flag = false;
					break;
				}
			}else {
				invinterUserId = null;
				flag = false;
				break;
			}
		}
		return ResponseUtil.ok(datas);
	}
	
	
	
	@ApiOperation(value = "修改用户的上级用户", notes = "修改用户的上级用户")
	@RequestMapping(value = "editParentUser", method = RequestMethod.POST)
	@ResponseBody
	public Response editParentUser(HttpServletRequest request, HttpServletResponse response,@RequestBody EditParentUserRequest editParentUserRequest) {
		logger.debug(">>>>>>>>修改用户的上级用户<<<<<<<<<<");
		EditParentUserResponse data = new EditParentUserResponse();
		User user = null;
		int i = 0;
		
		user = new User();
		user.setId(editParentUserRequest.getUserId());
		user.setInviterUserId(editParentUserRequest.getParentUserId());
		
		 i = userService.update(user);
		if (i<=0) {
			return ResponseUtil.error(ErrorCode.UPDATE_DATA_ERROR, "修改用户的上级用户失败!");
		}
		
		return ResponseUtil.ok(data);
	}
	
	@ApiOperation(value = "添加用户的上级用户", notes = "添加用户的上级用户")
	@RequestMapping(value = "addParentUser", method = RequestMethod.POST)
	@ResponseBody
	public Response addParentUser(@CurrentUserId Long userId,@RequestBody User user){
		int success =0;
		
		User user2 = userService.get(user.getId());
		
		if (user2.getType() > user.getLevel()) {
			user.setType(user.getLevel());
			 success = userService.update(user);
		}
		return ResponseUtil.ok(success);
	}
	
	@ApiOperation(value = "重置安全码", notes = "重置安全码")
	@RequestMapping(value = "updateSafeCode", method = RequestMethod.POST)
	@ResponseBody
	public Response updateSafeCode(@CurrentUserId Long userId,@RequestBody SafetyCode safetyCode){
		int success = safetyCodeService.HandleDeleteCode(safetyCode);
		return ResponseUtil.ok(success);
	}
	
	@ApiOperation(value = "购买会员卡列表", notes = "购买会员卡列表")
	@RequestMapping(value = "userMember", method = RequestMethod.POST)
	@ResponseBody
	public Response userMember(@RequestBody UserMember userMember){
		 Page<UserMember> page= userMemberService.page(userMember);
		return ResponseUtil.ok(page);
	}
	
	@ApiOperation(value = "会员卡列表", notes = "会员卡列表")
	@RequestMapping(value = "vipList", method = RequestMethod.POST)
	@ResponseBody
	public Response vipList(@RequestBody UserVip userVip){
		userVip.setOrderBy("USER_VIP.integral");
		 Page<UserVip> page= userVipService.page(userVip);
		return ResponseUtil.ok(page);
	}
	
	@ApiOperation(value = "会员卡设置新增", notes = "会员卡设置新增")
	@RequestMapping(value = "vipAdd", method = RequestMethod.POST)
	@ResponseBody
	public Response vipAdd(@RequestBody UserVip userVip){
		 userVip.setUpdateTime(new Timestamp(new Date().getTime()));
		 boolean result= userVipService.insert(userVip);
		 if (result==true) {
			 return ResponseUtil.ok(1);
		}
		return ResponseUtil.ok(0);
	}

	@ApiOperation(value = "会员卡设置编辑", notes = "会员卡设置编辑")
	@RequestMapping(value = "vipUpdate", method = RequestMethod.POST)
	@ResponseBody
	public Response vipUpdate(@RequestBody UserVip userVip){
		 userVip.setUpdateTime(new Timestamp(new Date().getTime()));
		 int result= userVipService.update(userVip);
		
		return ResponseUtil.ok(result);
	}
	
	@ApiOperation(value = "会员卡设置删除", notes = "会员卡设置删除")
	@RequestMapping(value = "vipRemove", method = RequestMethod.POST)
	@ResponseBody
	public Response vipRemove(@RequestBody UserVip userVip){
		 int result= userVipService.remove(userVip);
		
		return ResponseUtil.ok(result);
	}

	
	private SysConfig getSysConfig(String field) {
		SysConfig sysConfig = null;
		Map<String, Object> params = new HashMap<String, Object>();
		params = new HashMap<String, Object>();
	 	params.put("field", field);
	 	sysConfig = sysConfigService.findOne(params);
		return sysConfig;
	}
	
	

}
